﻿Imports System.Data.Objects
Imports System.Linq
Imports System.Collections.ObjectModel

Friend Class EntityObservableCollection(Of T As Class)
    Inherits ObservableCollection(Of T)
    Private ReadOnly objectSet As IObjectSet(Of T)


    Public Sub New(objectSet As IObjectSet(Of T))
        MyBase.New(If(DirectCast(objectSet, IEnumerable(Of T)), New T() {}))
        If objectSet Is Nothing Then
            Throw New ArgumentNullException("objectSet")
        End If
        Me.objectSet = objectSet
    End Sub


    Protected Overrides Sub InsertItem(index As Integer, item As T)
        objectSet.AddObject(item)

        MyBase.InsertItem(index, item)
    End Sub

    Protected Overrides Sub RemoveItem(index As Integer)
        Dim itemToDelete As T = Me(index)
        objectSet.DeleteObject(itemToDelete)

        MyBase.RemoveItem(index)
    End Sub

    Protected Overrides Sub ClearItems()
        Dim itemsToDelete As T() = ToArray()
        For Each _item As T In itemsToDelete
            objectSet.DeleteObject(_item)
        Next

        MyBase.ClearItems()
    End Sub

    Protected Overrides Sub SetItem(index As Integer, item As T)
        Dim itemToReplace As T = Me(index)
        objectSet.DeleteObject(itemToReplace)
        objectSet.AddObject(item)

        MyBase.SetItem(index, item)
    End Sub
End Class

